<template>
  <div class="doctor-dashboard">
    <!-- 顶部导航栏 -->
    <el-container>
      <el-header class="header">
        <!-- 左上角：系统名称 -->
        <div class="header-left">
          <span class="system-title">就诊管理系统</span>
        </div>
        <!-- 右上角：欢迎文案 + 退出登录 + 功能按钮 -->
        <div class="header-right">
          <span class="welcome-msg">欢迎，{{ username }}</span>
          <el-button type="danger" @click="handleLogout" class="logout-btn">退出登录</el-button>
          <el-button 
            circle 
            size="small" 
            class="header-btn" 
            @click="goToSystemSetting"
            title="系统设置"
          >
            <el-icon><Setting /></el-icon>
          </el-button>
          <el-button 
            circle 
            size="small" 
            class="header-btn"
            title="通知中心"
          >
            <el-icon><Notification /></el-icon>
          </el-button>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏导航 -->
        <el-aside width="200px" class="sidebar">
          <el-menu
            :default-active="$route.path"  
            class="el-menu-vertical-demo"
            background-color="#0f172a"
            text-color="#e2e8f0"
            active-text-color="#fff"
            router  
          >
            <el-menu-item index="/home/dashboard">
              <span>工作台</span>
            </el-menu-item>
            <el-menu-item index="/home/registration">
              <span>挂号列表</span>
            </el-menu-item>
            <el-menu-item index="/home/consultation-record">
              <span>就诊记录</span>
            </el-menu-item>
            <el-menu-item index="/home/scheduling">
              <span>排班设置</span>
            </el-menu-item>
            <el-menu-item index="/home/userManagement">
              <span>用户管理</span>
            </el-menu-item>
            <el-menu-item index="/home/operationLog">
              <span>操作日志</span>
            </el-menu-item>
            <el-menu-item index="/home/roleManagement">
              <span>角色管理</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主内容区域（路由视图） -->
        <el-main class="main-content">
          <router-view 
            @view-details="handleViewDetails"
            @update-patient="updatePatient"
          ></router-view>
        </el-main>
      </el-container>
    </el-container>

    <!-- 就诊详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="患者就诊详情"
      :width="800"
      :before-close="handleDialogClose"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <div class="patient-basic-info">
              <div class="info-item">
                <span class="info-label">姓名：</span>
                <span class="info-value">{{ currentPatient.patientName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">性别：</span>
                <span class="info-value">{{ currentPatient.gender || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">年龄：</span>
                <span class="info-value">{{ currentPatient.age || '-' }}岁</span>
              </div>
              <div class="info-item">
                <span class="info-label">挂号单号：</span>
                <span class="info-value">{{ currentPatient.registrationNo || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">科室：</span>
                <span class="info-value">{{ currentPatient.dept_name || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">就诊号：</span>
                <span class="info-value">{{ currentPatient.visit_no || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">挂号时间：</span>
                <span class="info-value">{{ currentPatient.registrationTime || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">就诊时间：</span>
                <span class="info-value">{{ currentPatient.visit_time ? formatDateTime(currentPatient.visit_time) : '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">症状描述：</span>
                <span class="info-value">{{ currentPatient.symptoms || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态：</span>
                <span class="info-value">
                  <el-tag :type="getStatusType(currentPatient.order_status)">
                    {{ currentPatient.status || '-' }}
                  </el-tag>
                </span>
              </div>
              <div class="info-item">
                <span class="info-label">医生：</span>
                <span class="info-value">{{ currentPatient.doctor_name || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">挂号费用：</span>
                <span class="info-value">¥{{ currentPatient.amount || '-' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="24">
          <el-card>
            <div slot="header">就诊记录</div>
            <el-form ref="consultFormRef" :model="consultForm" label-width="100px">

              <el-form-item label="主诉：">
                <el-input 
                  v-if="consultForm.chiefComplaint !== undefined"
                  v-model="consultForm.chiefComplaint" 
                  type="textarea" 
                  rows="2" 
                  placeholder="请输入患者主诉..."
                />
              </el-form-item>
              <el-form-item label="现病史：">
                <el-input 
                  v-if="consultForm.presentIllness !== undefined"
                  v-model="consultForm.presentIllness" 
                  type="textarea" 
                  rows="3" 
                  placeholder="请输入现病史..."
                />
              </el-form-item>
              <el-form-item label="体格检查：">
                <el-input 
                  v-if="consultForm.examinationResult !== undefined"
                  v-model="consultForm.examinationResult" 
                  type="textarea" 
                  rows="3" 
                  placeholder="请输入体格检查结果..."
                />
              </el-form-item>
              <el-form-item label="辅助检查：">
                <el-input 
                  v-if="consultForm.auxiliaryExam !== undefined"
                  v-model="consultForm.auxiliaryExam" 
                  type="textarea" 
                  rows="3" 
                  placeholder="请输入辅助检查结果..."
                />
              </el-form-item>
              <el-form-item label="诊断结果：">
                <el-input 
                  v-if="consultForm.diagnosis !== undefined"
                  v-model="consultForm.diagnosis" 
                  type="textarea" 
                  rows="2" 
                  placeholder="请输入诊断结果..."
                />
              </el-form-item>
              <el-form-item label="治疗方案：">
                <el-input 
                  v-if="consultForm.treatmentPlan !== undefined"
                  v-model="consultForm.treatmentPlan" 
                  type="textarea" 
                  rows="2" 
                  placeholder="请输入治疗方案..."
                />
              </el-form-item>
              <el-form-item label="建议复诊日期：">
                <el-date-picker
                  v-model="consultForm.nextVisitDate"
                  type="date"
                  placeholder="选择复诊日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="24">
          <el-card>
            <div slot="header">医嘱</div>
            <el-form-item>
              <el-input 
                v-if="medicalAdvice !== undefined"
                v-model="medicalAdvice" 
                type="textarea" 
                rows="4" 
                placeholder="请输入医嘱内容..."
              />
            </el-form-item>
            <el-button type="primary" @click="saveMedicalAdvice">保存医嘱</el-button>
          </el-card>
        </el-col>

        <el-col :span="24">
          <el-card>
            <div slot="header">
              处方开具
              <el-button 
                link 
                size="small" 
                @click="showMedicineDialog = true"
                class="add-medicine-btn"
              >
                添加药品
              </el-button>
            </div>
            <el-table
              :data="prescriptionMedicines"
              border
              style="width: 100%; margin-bottom: 15px"
            >
              <el-table-column prop="name" label="药品名称" />
              <el-table-column prop="specification" label="规格" />
              <el-table-column prop="dosage" label="剂量" />
              <el-table-column prop="frequency" label="频次" />
              <el-table-column prop="days" label="天数" />
              <el-table-column prop="usage" label="用法" />
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button 
                    size="small" 
                    type="text" 
                    text-color="#ff4d4f"
                    @click="removeMedicine(scope.$index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" @click="savePrescription">保存处方</el-button>
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          type="success" 
          @click="saveMedicalRecord"
        >
          保存记录
        </el-button>
        <el-button 
          type="primary" 
          @click="confirmCompleteConsultation"
          v-if="currentPatient.order_status === 4"
        >
          完成就诊
        </el-button>
      </template>
    </el-dialog>

    <!-- 药品选择对话框 -->
    <el-dialog
      v-model="showMedicineDialog"
      title="选择药品"
      :width="600"
    >
      <el-input 
        v-model="medicineSearch" 
        placeholder="搜索药品名称..." 
        class="medicine-search"
      />
      <el-table
        :data="filteredMedicines"
        border
        style="width: 100%; margin-top: 15px"
        @row-click="selectMedicine"
      >
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="name" label="药品名称" />
        <el-table-column prop="specification" label="规格" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="usage" label="常用用法" />
      </el-table>

      <template #footer>
        <el-button @click="showMedicineDialog = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, triggerRef, watch } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import axiosInstance from '../axios/axiosInstance.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Setting, Notification, User } from '@element-plus/icons-vue'; 

// 定义emit事件
const emit = defineEmits(['view-details', 'update-patient']);

const router = useRouter();
const username = ref('张医生'); // 可动态绑定用户姓名

// 系统设置页面跳转
const goToSystemSetting = () => {
  router.push('/home/system-setting');
};

// 对话框状态管理
const detailDialogVisible = ref(false);
const showMedicineDialog = ref(false);
const currentPatient = ref({});
const medicalAdvice = ref('');
const medicineSearch = ref('');
const prescriptionMedicines = ref([]);

// 就诊表单数据
const consultForm = reactive({
  chiefComplaint: '',
  presentIllness: '',
  examinationResult: '',
  auxiliaryExam: '',
  diagnosis: '',
  treatmentPlan: '',
  nextVisitDate: ''
});

const consultFormRef = ref(null);

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateTimeStr;
  }
};

// 获取状态类型
const getStatusType = (orderStatus) => {
  switch (orderStatus) {
    case 1: return 'warning'; // 未就诊 - 黄色
    case 3: return 'success'; // 已就诊 - 绿色
    case 4: return 'primary'; // 就诊中 - 蓝色
    default: return 'info';
  }
};

// 获取状态文本
const getStatusText = (orderStatus) => {
  switch (orderStatus) {
    case 1: return '未就诊';
    case 3: return '已就诊';
    case 4: return '就诊中';
    default: return '未知';
  }
};

// 转换患者数据格式
const convertPatientData = (row) => {
  return {
    id: row.order_id,
    patientName: row.patient_name,
    gender: row.gender_text,
    age: row.age,
    registrationNo: row.order_no,
    registrationTime: formatDateTime(row.create_time),
    symptoms: row.symptoms,
    status: getStatusText(row.order_status),
    order_status: row.order_status,
    visit_no: row.visit_no,
    dept_name: row.dept_name,
    visit_time: row.visit_time,
    update_time: row.update_time,
    order_id: row.order_id,
    patient_id: row.patient_id,
    doctor_id: row.doctor_id,
    doctor_name: row.doctor_name,
    amount: row.amount
  };
};

// 药品数据
const medicines = ref([
  { id: 1, name: '阿司匹林肠溶片', specification: '100mg', unit: '片', usage: '口服' },
  { id: 2, name: '布洛芬缓释胶囊', specification: '0.3g', unit: '粒', usage: '口服' },
  { id: 3, name: '头孢克肟分散片', specification: '100mg', unit: '片', usage: '口服' },
  { id: 4, name: '盐酸氨溴索口服溶液', specification: '100ml', unit: '瓶', usage: '口服' },
  { id: 5, name: '复方甘草片', specification: '100片/瓶', unit: '瓶', usage: '口服' }
]);

// 药品搜索过滤
const filteredMedicines = computed(() => {
  return medicineSearch.value 
    ? medicines.value.filter(med => med.name.includes(medicineSearch.value)) 
    : medicines.value;
});

// 退出登录
const handleLogout = () => {
  router.push('/login');
};

// 查看患者详情
const handleViewDetails = async (row) => {
  currentPatient.value = { ...row };
  
  // 先打开对话框
  detailDialogVisible.value = true;
  
  // 等待对话框渲染完成后再填充数据
  await nextTick();
  
  // 如果有就诊记录，填充表单数据
  if (row.medicalRecord) {
    const record = row.medicalRecord;
    
    // 直接赋值确保响应式更新
    consultForm.chiefComplaint = record.chief_complaint || '';
    consultForm.presentIllness = record.present_illness || '';
    consultForm.examinationResult = record.physical_exam || '';
    consultForm.auxiliaryExam = record.auxiliary_exam || '';
    consultForm.diagnosis = record.diagnosis || '';
    consultForm.treatmentPlan = record.treatment_plan || '';
    consultForm.nextVisitDate = record.next_visit_date ? record.next_visit_date.split('T')[0] : '';
    
    medicalAdvice.value = record.advice || '';
    
    // 强制更新表单
    await nextTick();
    
    // 强制更新组件
    await nextTick();
    
    // 延迟设置值，确保DOM完全渲染
    setTimeout(() => {
      // 强制触发响应式更新
      const temp = consultForm.chiefComplaint;
      consultForm.chiefComplaint = '';
      setTimeout(() => {
        consultForm.chiefComplaint = temp;
      }, 10);
      
      // 直接操作DOM设置值
      if (consultFormRef.value) {
        const textareas = consultFormRef.value.$el.querySelectorAll('textarea');
        textareas.forEach((textarea, index) => {
                  const values = [
          consultForm.chiefComplaint,
          consultForm.presentIllness,
          consultForm.examinationResult,
          consultForm.auxiliaryExam,
          consultForm.diagnosis,
          consultForm.treatmentPlan
        ];
          if (values[index]) {
            textarea.value = values[index];
            // 触发input事件
            textarea.dispatchEvent(new Event('input', { bubbles: true }));
          }
        });
      }
    }, 100);
    
    // 如果有处方信息，可以解析并添加到处方列表
    if (record.prescription) {
      prescriptionMedicines.value = [{
        name: record.prescription,
        specification: '',
        dosage: '',
        frequency: '',
        days: '',
        usage: ''
      }];
    } else {
      prescriptionMedicines.value = [];
    }
  } else {
    // 如果没有就诊记录，清空表单
    Object.keys(consultForm).forEach(key => consultForm[key] = '');
    medicalAdvice.value = '';
    prescriptionMedicines.value = [];
  }
};

// 更新患者信息
const updatePatient = (updatedPatient) => {
  currentPatient.value = updatedPatient;
};

// 关闭详情对话框
const handleDialogClose = () => {
  detailDialogVisible.value = false;
};

// 保存医嘱
const saveMedicalAdvice = () => {
  // 需要先获取record_id，如果没有则提示用户先保存就诊记录
  if (!currentPatient.value.medicalRecord || !currentPatient.value.medicalRecord.record_id) {
    ElMessage.warning('请先保存就诊记录，再保存医嘱');
    return;
  }
  
  const params = {
    record_id: currentPatient.value.medicalRecord.record_id,
    advice: medicalAdvice.value
  };
  
  console.log('保存医嘱参数:', params);
  
  axiosInstance.post('/saveAdvice', null, { params })
    .then(res => {
      console.log('医嘱保存成功', res.data);
      ElMessage.success('医嘱保存成功');
    })
    .catch(err => {
      console.error('医嘱保存失败', err);
      ElMessage.error('医嘱保存失败');
    });
};

// 选择药品
const selectMedicine = (medicine) => {
  prescriptionMedicines.value.push({
    ...medicine,
    dosage: '1',
    frequency: '每日3次',
    days: 3
  });
  showMedicineDialog.value = false;
};

// 移除药品
const removeMedicine = (index) => {
  prescriptionMedicines.value.splice(index, 1);
};

// 保存处方
const savePrescription = () => {
  const prescriptionData = {
    patient_id: currentPatient.value.patient_id,
    order_id: currentPatient.value.order_id,
    doctor_id: currentPatient.value.doctor_id || 1,
    prescription: prescriptionMedicines.value.map(med => med.name).join(', '),
    medicines: prescriptionMedicines.value
  };
  
  axiosInstance.post('/prescription', prescriptionData)
    .then(res => {
      console.log('处方保存成功', res.data);
      ElMessage.success('处方保存成功');
    })
    .catch(err => {
      console.error('处方保存失败', err);
      ElMessage.error('处方保存失败');
    });
};

// 保存就诊记录
const saveMedicalRecord = () => {
  const consultationData = {
    patient_id: currentPatient.value.patient_id,
    doctor_id: currentPatient.value.doctor_id || 1,
    order_id: currentPatient.value.order_id,
    visit_date: new Date().toISOString().split('T')[0], // 格式：YYYY-MM-DD
    chief_complaint: consultForm.chiefComplaint,
    present_illness: consultForm.presentIllness,
    physical_exam: consultForm.examinationResult,
    auxiliary_exam: consultForm.auxiliaryExam,
    diagnosis: consultForm.diagnosis,
    treatment_plan: consultForm.treatmentPlan,
    prescription: prescriptionMedicines.value.map(med => med.name).join(', '),
    advice: medicalAdvice.value,
    next_visit_date: consultForm.nextVisitDate || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 使用表单中的日期或默认30天后复诊
    status: 1 // 1 - 有效
  };
  
  console.log('准备保存的就诊数据:', consultationData);
  
  // 使用axiosInstance确保使用正确的baseURL
  axiosInstance.post('/update', consultationData)
    .then(res => {
      console.log('就诊记录保存成功', res.data);
      ElMessage.success('就诊记录保存成功');
    })
    .catch(err => {
      console.error('就诊记录保存失败', err);
      ElMessage.error('就诊记录保存失败');
    });
};

// 确认完成就诊
const confirmCompleteConsultation = () => {
  ElMessageBox.confirm(
    '确认完成就诊吗？完成就诊后患者状态将更新为"已就诊"。',
    '确认完成就诊',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      completeConsultation();
    })
    .catch(() => {
      // 用户取消
    });
};

// 完成就诊
const completeConsultation = () => {
  const consultationData = {
    patient_id: currentPatient.value.patient_id,
    doctor_id: currentPatient.value.doctor_id || 1,
    order_id: currentPatient.value.order_id,
    visit_date: new Date().toISOString().split('T')[0], // 格式：YYYY-MM-DD
    chief_complaint: consultForm.chiefComplaint,
    present_illness: consultForm.presentIllness,
    physical_exam: consultForm.examinationResult,
    auxiliary_exam: consultForm.auxiliaryExam,
    diagnosis: consultForm.diagnosis,
    treatment_plan: consultForm.treatmentPlan,
    prescription: prescriptionMedicines.value.map(med => med.name).join(', '),
    advice: medicalAdvice.value,
    next_visit_date: consultForm.nextVisitDate || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 使用表单中的日期或默认30天后复诊
    status: 1 // 1 - 有效
  };
  
  console.log('准备保存的就诊数据:', consultationData);
  
  // 先保存就诊记录
  axiosInstance.post('/update', consultationData)
    .then(res => {
      console.log('就诊记录保存成功', res.data);
      ElMessage.success('就诊记录保存成功');
      
      // 然后更新患者状态为已就诊
      return axiosInstance.put(`/${currentPatient.value.order_id}/status`, null, { 
        params: { status: 3 } 
      });
    })
    .then(res => {
      console.log('患者状态更新成功', res.data);
      ElMessage.success('完成就诊成功');
      detailDialogVisible.value = false;
      
      // 通知父组件更新患者状态
      emit('update-patient', convertPatientData(res.data));
    })
    .catch(err => {
      console.error('完成就诊失败', err);
      ElMessage.error('完成就诊失败');
    });
};
</script>

<style scoped>
.doctor-dashboard { 
  height: 100vh; 
  display: flex; 
  flex-direction: column; 
  background-color: #f1f5f9; 
}

.header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  padding: 0 20px; 
  height: 60px; 
  background-color: #fff; 
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); 
}

.header-left {
  display: flex;
  align-items: center;
}

.system-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome-msg {
  color: #64748b;
}

.logout-btn {
  margin-left: 10px;
}

.header-btn {
  color: #64748b;
  transition: color 0.3s;
}

.header-btn:hover {
  color: #1e293b;
}

.sidebar { 
  background-color: #0f172a; 
  height: calc(100vh - 60px); 
}

.main-content { 
  padding: 20px; 
  overflow-y: auto; 
  height: calc(100vh - 60px); 
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #1e293b;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.patient-basic-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  color: #64748b;
  width: 80px;
}

.info-value {
  font-weight: 500;
}

.add-medicine-btn {
  float: right;
  color: #3b82f6;
}

.medicine-search {
  width: 100%;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 0 15px 15px;
}
</style>
